package xyz.huanggy.minio.upload.controller;


import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;
import xyz.huanggy.minio.upload.model.dto.Result;
import xyz.huanggy.minio.upload.model.entity.SysUploadTask;
import xyz.huanggy.minio.upload.properties.MinioProperties;
import xyz.huanggy.minio.upload.service.SysUploadTaskService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;


/**
 * 分片上传-分片任务记录(SysUploadTask)表控制层
 *
 * @since 2022-08-22 17:47:31
 */
@RestController
@RequestMapping("/test")
public class MinioTestController {
    /**
     * 服务对象
     */
    @Resource
    private SysUploadTaskService sysUploadTaskService;

    @Resource
    private AmazonS3 amazonS3;

    @Resource
    private MinioProperties minioProperties;


    /**
     * 获取上传进度
     * @param key 文件md5
     * @return
     */
    @GetMapping("/getUrl/{key}")
    public Result taskInfo (@PathVariable("key") String key) {
        String bucketName = minioProperties.getBucket();
        GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(bucketName, key);
        String s1 = amazonS3.generatePresignedUrl(httpRequest).toString();
        String url = amazonS3.getUrl(bucketName, key).toString();
        System.out.println("s1-->"+s1);
        System.out.println("url-->"+url);
        return Result.ok(url);
    }


    @GetMapping(value="/downloadkey/{key}")
    public void downloadkey(@PathVariable("key") Long key,HttpServletRequest request){
        SysUploadTask byId = sysUploadTaskService.getById(key);
        String objectKey = byId.getObjectKey();
        String bucketName = byId.getBucketName();
        S3Object s3object = amazonS3.getObject(new GetObjectRequest(bucketName, objectKey));
        InputStream inputStream = s3object.getObjectContent();
        try {
            Path path = Paths.get("D:\\Downloads\\" + objectKey);
            if(!Files.isDirectory(path)){
                Path dirPath = path.getParent();
                if(!Files.exists(dirPath)){
                    Files.createDirectories(dirPath);
                }
            }
            Files.copy(inputStream, Paths.get("D:\\Downloads\\"+objectKey), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @GetMapping(value="/download/{key}/**")
    public void download(@PathVariable String key,HttpServletRequest request){
        String bucketName = minioProperties.getBucket();
        // String filepath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String filepath = getExtractPath(key,request);
        S3Object s3object = amazonS3.getObject(new GetObjectRequest(bucketName, filepath));
        InputStream inputStream = s3object.getObjectContent();
        try {
            Files.copy(inputStream, Paths.get("D:\\Downloads"), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    private String getExtractPath(String key,HttpServletRequest request) {
        //用于获取请求全路径： /download/2023-05-05/test.jpg
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        //用户获取匹配到controller的路径：/download/{key}/**
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        //使用 AntPathMatcher 匹配所需要的URL : test.jpg
        String arguments = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
        if(StringUtils.isNotBlank(key))
            return key + "/" + arguments;
        return arguments;
    }
}
